import qs from 'qs';
export default {
  data() {
    return {
      // 下载用到的 notification组件对象键值对
      notifications: {}
    };
  },
  methods: {
    /**
     * 同步下载，利用浏览器自带的文件下载功能
     * @param {string} url - 接口地址
     * @param {Object} [params=null] - 下载参数，qs.stringify会将该对像转为形如：id=123&name=Ada
     * @param {string} [filename=''] - 下载文件名
     */
    downloadFile(url, params = null, filename = '') {
      const el = document.createElement('a');
      el.style.display = 'none';
      document.body.appendChild(el);
      filename && el.setAttribute('download', filename);
      const queryStr = [qs.stringify(params)].map(item => item && `?${item}`)[0];
      el.href = this.$tool.getFullUrl(url + queryStr);
      el.click();
      document.body.removeChild(el);
    },
    /**
     * 异步-带header(token)
     * @param {string} [method='GET'] - 请求方法get/post(不区分大小写)
     * @param {string} url - 接口地址
     * @param {Object} params - 下载参数，get格式为：?id=123&&name="文件下载"
     * @param {string} filename - 下载文件名(必填，若为空，下载下来都是txt格式)
     * @param {Object} [config={}] - 异步请求其它配置
     */
    async downloadFileAsync(method = 'GET', url, params, filename, config = {}) {
      const actionId = Date.now();
      const res = await this.$request.ajax(method, url, params, Object.assign({
        baseURL: '/download',
        responseType: 'blob',
        transformResponse: this.transformResponse,
        onDownloadProgress: event => this.downloadProgress(event, actionId, filename)
      }, config));
      if (res.status === 200) {
        const fileReader = new FileReader();
        fileReader.readAsText(res.data);
        fileReader.onload = () => {
          try {
            // 考虑后端返回的不是文件流是错误描述对象的情况
            const jsonData = JSON.parse(fileReader.result);
            this.$message.error(jsonData.message);
          } catch (err) {
            const blob = new Blob([res.data]);
            const fileUrl = URL.createObjectURL(blob);
            this.downloadFile(fileUrl, null, filename || res.headers['content-disposition'] || '下载文件名');
            URL.revokeObjectURL(fileUrl);
            this.$message.success('文件已生成');
          }
        };
      } else {
        this.$message.error('文件获取失败，请稍后再试。');
      }
    },
    // 文件下载响应头格式
    transformResponse(data) {
      return {
        data,
        status: data ? 200 : 500
      };
    },
    // 文件下载进度 actionId：时间戳-标识此次的下载事件
    downloadProgress({loaded, total}, actionId, filename = '') {
      const message = `${filename}<br/>${(loaded / total * 100).toFixed(2)}%（${loaded} / ${total}）`;
      if (!this.notifications[actionId]) {
        this.notifications[actionId] = this.$notify.info({
          title: '文件生成进度',
          message,
          position: 'bottom-left',
          dangerouslyUseHTMLString: true,
          duration: 0
        });
      } else {
        this.notifications[actionId].message = message;
      }
      if (this.notifications[actionId] && total === loaded) this.notifications[actionId].close();
    }
  }
};
